import 'package:flutter/foundation.dart';
import '../models/hot_item.dart';
import '../models/comment.dart';

class HotItemProvider extends ChangeNotifier {
  List<HotItem> _hotItems = [];
  List<HotItem> _filteredItems = [];
  bool _isLoading = false;
  bool _isInitialized = false;
  String _searchKeyword = '';
  HotItemType? _selectedType;
  SortType _sortType = SortType.none;

  List<HotItem> get hotItems => _hotItems;

  List<HotItem> get filteredItems => _filteredItems;

  List<HotItem> get recommendedItems =>
      _hotItems.where((item) => item.isRecommended).toList();

  List<HotItem> getUserPublishedItems(String userId) {
    return _hotItems.where((item) => item.publisherId == userId).toList();
  }

  List<HotItem> getUserFavoriteItems(String userId) {
    return _hotItems.take(3).toList();
  }

  bool get isLoading => _isLoading;

  String get searchKeyword => _searchKeyword;

  HotItemType? get selectedType => _selectedType;

  SortType get sortType => _sortType;

  Future<void> initialize() async {
    if (_isInitialized) return;

    _setLoading(true);

    await Future.delayed(const Duration(milliseconds: 500));

    _hotItems = _getMockData();
    _initializeMockComments();
    _isInitialized = true;

    _setLoading(false);
  }

  Future<void> refresh() async {
    await initialize();
  }

  void searchItems(String keyword) {
    _searchKeyword = keyword;
    notifyListeners();
  }

  void filterByType(HotItemType? type) {
    _selectedType = type;
    notifyListeners();
  }

  void sortItems(SortType sortType) {
    _sortType = sortType;
    notifyListeners();
  }

  void addItem(HotItem item) {
    _hotItems.add(item);
    notifyListeners();
  }

  void updateItem(HotItem updatedItem) {
    final index = _hotItems.indexWhere((item) => item.id == updatedItem.id);
    if (index != -1) {
      _hotItems[index] = updatedItem;
      notifyListeners();
    }
  }

  void removeItem(String id) {
    _hotItems.removeWhere((item) => item.id == id);
    notifyListeners();
  }

  HotItem? getItemById(String id) {
    try {
      return _hotItems.firstWhere((item) => item.id == id);
    } catch (e) {
      return null;
    }
  }

  final Set<String> _likedItems = <String>{};

  final Map<String, List<Comment>> _itemComments = <String, List<Comment>>{};

  bool isLiked(String itemId) {
    return _likedItems.contains(itemId);
  }

  void toggleLike(String itemId) {
    final item = getItemById(itemId);
    if (item != null) {
      if (_likedItems.contains(itemId)) {
        _likedItems.remove(itemId);
        final updatedItem = item.copyWith(likeCount: item.likeCount - 1);
        updateItem(updatedItem);
      } else {
        _likedItems.add(itemId);
        final updatedItem = item.copyWith(likeCount: item.likeCount + 1);
        updateItem(updatedItem);
      }
    }
  }

  void likeItem(String id) {
    if (!_likedItems.contains(id)) {
      toggleLike(id);
    }
  }

  void commentItem(String id) {
    final item = getItemById(id);
    if (item != null) {
      final updatedItem = item.copyWith(commentCount: item.commentCount + 1);
      updateItem(updatedItem);
    }
  }

  List<Comment> getCommentsForItem(String itemId) {
    return _itemComments[itemId] ?? [];
  }

  void addComment({
    required String itemId,
    required String userId,
    required String userName,
    required String userAvatar,
    required String content,
  }) {
    final commentId = 'comment_${DateTime.now().millisecondsSinceEpoch}';
    final now = DateTime.now();

    final newComment = Comment(
      id: commentId,
      hotItemId: itemId,
      userId: userId,
      userName: userName,
      userAvatar: userAvatar,
      content: content,
      createdAt: now,
      updatedAt: now,
    );

    if (_itemComments[itemId] == null) {
      _itemComments[itemId] = [];
    }
    _itemComments[itemId]!.add(newComment);

    final item = getItemById(itemId);
    if (item != null) {
      final updatedItem = item.copyWith(commentCount: item.commentCount + 1);
      updateItem(updatedItem);
    }

    notifyListeners();
  }

  void deleteComment(String itemId, String commentId) {
    final comments = _itemComments[itemId];
    if (comments != null) {
      comments.removeWhere((comment) => comment.id == commentId);

      final item = getItemById(itemId);
      if (item != null) {
        final updatedItem = item.copyWith(commentCount: item.commentCount - 1);
        updateItem(updatedItem);
      }

      notifyListeners();
    }
  }

  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }

  void _initializeMockComments() {
    final now = DateTime.now();

    _itemComments['hot_001'] = [
      Comment(
        id: 'comment_001',
        hotItemId: 'hot_001',
        userId: 'default_user_002',
        userName: '',
        userAvatar: '',
        content:
            'Beautiful guitar! The wood grain looks amazing. What brand is it? 🎸✨',
        createdAt: now.subtract(const Duration(hours: 3)),
        updatedAt: now.subtract(const Duration(hours: 3)),
      ),
      Comment(
        id: 'comment_002',
        hotItemId: 'hot_001',
        userId: 'default_user_003',
        userName: '',
        userAvatar: '',
        content:
            'The sound quality must be incredible! Can\'t wait to hear you play it 🎶',
        createdAt: now.subtract(const Duration(hours: 1)),
        updatedAt: now.subtract(const Duration(hours: 1)),
      ),
      Comment(
        id: 'comment_003',
        hotItemId: 'hot_001',
        userId: 'default_user_004',
        userName: '',
        userAvatar: '',
        content: 'As a beginner, this inspires me to keep practicing! 💪',
        createdAt: now.subtract(const Duration(minutes: 45)),
        updatedAt: now.subtract(const Duration(minutes: 45)),
      ),
    ];

    _itemComments['hot_002'] = [
      Comment(
        id: 'comment_004',
        hotItemId: 'hot_002',
        userId: 'default_user_001',
        userName: '',
        userAvatar: '',
        content:
            'Your dedication really shows! That\'s what practice is all about 🎸',
        createdAt: now.subtract(const Duration(hours: 2)),
        updatedAt: now.subtract(const Duration(hours: 2)),
      ),
      Comment(
        id: 'comment_005',
        hotItemId: 'hot_002',
        userId: 'default_user_005',
        userName: '',
        userAvatar: '',
        content: 'Flawless performance! Keep up the excellent work 👏',
        createdAt: now.subtract(const Duration(minutes: 20)),
        updatedAt: now.subtract(const Duration(minutes: 20)),
      ),
    ];

    _itemComments['hot_003'] = [
      Comment(
        id: 'comment_006',
        hotItemId: 'hot_003',
        userId: 'default_user_006',
        userName: '',
        userAvatar: '',
        content:
            'Arpeggios are so important for finger independence. Great work! 🎹',
        createdAt: now.subtract(const Duration(hours: 4)),
        updatedAt: now.subtract(const Duration(hours: 4)),
      ),
      Comment(
        id: 'comment_007',
        hotItemId: 'hot_003',
        userId: 'default_user_002',
        userName: '',
        userAvatar: '',
        content: 'Daily practice really makes a difference. Keep it up! 💪',
        createdAt: now.subtract(const Duration(hours: 1, minutes: 30)),
        updatedAt: now.subtract(const Duration(hours: 1, minutes: 30)),
      ),
    ];

    _itemComments['hot_004'] = [
      Comment(
        id: 'comment_008',
        hotItemId: 'hot_004',
        userId: 'default_user_001',
        userName: '',
        userAvatar: '',
        content: 'That groove sounds tight! Love the consistency 🥁🔥',
        createdAt: now.subtract(const Duration(hours: 2, minutes: 15)),
        updatedAt: now.subtract(const Duration(hours: 2, minutes: 15)),
      ),
      Comment(
        id: 'comment_009',
        hotItemId: 'hot_004',
        userId: 'default_user_003',
        userName: '',
        userAvatar: '',
        content: 'Amazing rhythm! Your timing is perfect 🎵',
        createdAt: now.subtract(const Duration(minutes: 50)),
        updatedAt: now.subtract(const Duration(minutes: 50)),
      ),
    ];

    _itemComments['hot_005'] = [
      Comment(
        id: 'comment_010',
        hotItemId: 'hot_005',
        userId: 'default_user_002',
        userName: '',
        userAvatar: '',
        content:
            'Original compositions are the best! This sounds beautiful 🎸🖤',
        createdAt: now.subtract(const Duration(hours: 3, minutes: 20)),
        updatedAt: now.subtract(const Duration(hours: 3, minutes: 20)),
      ),
    ];

    _itemComments['hot_006'] = [
      Comment(
        id: 'comment_011',
        hotItemId: 'hot_006',
        userId: 'default_user_004',
        userName: '',
        userAvatar: '',
        content: 'That piano looks and sounds amazing! What model is it? 🎹',
        createdAt: now.subtract(const Duration(hours: 1, minutes: 40)),
        updatedAt: now.subtract(const Duration(hours: 1, minutes: 40)),
      ),
      Comment(
        id: 'comment_012',
        hotItemId: 'hot_006',
        userId: 'default_user_005',
        userName: '',
        userAvatar: '',
        content:
            'Digital pianos have come so far! The expression is incredible 🎶',
        createdAt: now.subtract(const Duration(minutes: 25)),
        updatedAt: now.subtract(const Duration(minutes: 25)),
      ),
    ];

    _itemComments['hot_007'] = [
      Comment(
        id: 'comment_013',
        hotItemId: 'hot_007',
        userId: 'default_user_003',
        userName: '',
        userAvatar: '',
        content:
            'Classic songs never get old! Your interpretation is fantastic 🎸✨',
        createdAt: now.subtract(const Duration(hours: 2, minutes: 30)),
        updatedAt: now.subtract(const Duration(hours: 2, minutes: 30)),
      ),
      Comment(
        id: 'comment_014',
        hotItemId: 'hot_007',
        userId: 'default_user_006',
        userName: '',
        userAvatar: '',
        content: 'The tone is perfect! What amp are you using? 🎵',
        createdAt: now.subtract(const Duration(minutes: 35)),
        updatedAt: now.subtract(const Duration(minutes: 35)),
      ),
    ];

    _itemComments['hot_008'] = [
      Comment(
        id: 'comment_015',
        hotItemId: 'hot_008',
        userId: 'default_user_002',
        userName: '',
        userAvatar: '',
        content: 'Those fills are creative! Love your personal style 🥁🔥',
        createdAt: now.subtract(const Duration(hours: 1, minutes: 15)),
        updatedAt: now.subtract(const Duration(hours: 1, minutes: 15)),
      ),
    ];

    _itemComments['hot_009'] = [
      Comment(
        id: 'comment_016',
        hotItemId: 'hot_009',
        userId: 'default_user_004',
        userName: '',
        userAvatar: '',
        content:
            'So emotional and beautiful! Music really does tell stories 🎹❤️',
        createdAt: now.subtract(const Duration(hours: 3, minutes: 45)),
        updatedAt: now.subtract(const Duration(hours: 3, minutes: 45)),
      ),
      Comment(
        id: 'comment_017',
        hotItemId: 'hot_009',
        userId: 'default_user_001',
        userName: '',
        userAvatar: '',
        content: 'Your expression through the keys is incredible! 🎶',
        createdAt: now.subtract(const Duration(minutes: 55)),
        updatedAt: now.subtract(const Duration(minutes: 55)),
      ),
    ];
  }

  List<HotItem> _getMockData() {
    return [
      HotItem(
        id: 'hot_002',
        publisherId: 'default_user_002',
        type: HotItemType.image,
        title: 'Guitar Performance',
        description:
            'After weeks of practice, I finally played through this song without a single mistake. It’s such a satisfying feeling to see improvement day by day. 🎶 #PracticePaysOff',
        commentCount: 89,
        likeCount: 2340,
        resourceUrl: 'assets/images/item2.png',
        isRecommended: true,
      ),
      HotItem(
        id: 'hot_003',
        publisherId: 'default_user_003',
        type: HotItemType.image,
        title: 'Piano Practice',
        description:
            'Practicing arpeggios has really improved my finger flow on the piano. It’s amazing how daily exercises can lead to such noticeable progress. 🎹 #KeepLearning.',
        commentCount: 67,
        likeCount: 890,
        resourceUrl: 'assets/images/item3.png',
        isRecommended: false,
      ),

      HotItem(
        id: 'hot_004',
        publisherId: 'default_user_004',
        type: HotItemType.image,
        title: 'Drum Practice Sharing',
        description:
            'Working on a steady 4/4 groove today, and everything just clicked into place perfectly. The consistency feels incredible on my drum kit! 🥁🔥',
        commentCount: 156,
        likeCount: 3200,
        resourceUrl: 'assets/images/item4.png',
        isRecommended: true,
      ),
      HotItem(
        id: 'hot_001',
        publisherId: 'default_user_001',
        type: HotItemType.image,
        title: 'Acoustic Guitar',
        description:
            'My new acoustic guitar just arrived, and the sound is richer than I imagined. Looking forward to starting my next practice session with this beauty! 🎸✨',
        commentCount: 128,
        likeCount: 1520,
        resourceUrl: 'assets/images/item1.png',
        isRecommended: true,
      ),
      HotItem(
        id: 'hot_005',
        publisherId: 'default_user_001',
        type: HotItemType.image,
        title: 'Guitar Original Music',
        description:
            'Here’s my latest original composition on guitar. I poured my emotions into every note, and this has to be one of my favorite creations so far. 🎸🖤',
        commentCount: 45,
        likeCount: 678,
        resourceUrl: 'assets/images/item5.png',
        isRecommended: false,
      ),
      HotItem(
        id: 'hot_007',
        publisherId: 'default_user_001',
        type: HotItemType.video,
        title: 'Classic Song',
        description:
            'I spent hours perfecting this classic song on my guitar today, and the tone was absolutely worth it. Timeless music always challenges and inspires me. 🎸✨',
        commentCount: 234,
        likeCount: 5467,
        resourceUrl: 'assets/videos/guitar1.mp4',
        thumbnailUrl: 'assets/images/guitar1.png',
        isRecommended: true,
      ),
      HotItem(
        id: 'hot_006',
        publisherId: 'default_user_006',
        type: HotItemType.image,
        title: 'Piano Feelings',
        description:
            'My new digital piano not only looks elegant with its sleek design, but it also has such warm, expressive sound. It’s an absolute joy to play. 🎶🎹',
        commentCount: 234,
        likeCount: 4560,
        resourceUrl: 'assets/images/item6.png',
        isRecommended: true,
      ),

      HotItem(
        id: 'hot_009',
        publisherId: 'default_user_001',
        type: HotItemType.video,
        title: 'Piano Performance',
        description:
            'Playing this emotional ballad on the piano made me appreciate how music can truly tell a story. Every key felt like its own chapter. 🎹❤️',
        commentCount: 234,
        likeCount: 5467,
        resourceUrl: 'assets/videos/piano1.mp4',
        thumbnailUrl: 'assets/images/piano1.png',
        isRecommended: true,
      ),
      HotItem(
        id: 'hot_008',
        publisherId: 'default_user_005',
        type: HotItemType.video,
        title: 'Drum Practice',
        description:
            'I’ve been experimenting with different drum fills this week, adding a personal touch to my grooves. It’s exciting to find my unique style coming out! 🥁🔥',
        commentCount: 234,
        likeCount: 5467,
        resourceUrl: 'assets/videos/drum1.mp4',
        thumbnailUrl: 'assets/images/drum1.png',
        isRecommended: false,
      ),
    ];
  }
}

/// Sort type enum
enum SortType {
  /// No sorting
  none,

  /// Sort by likes descending
  likeDesc,

  /// Sort by likes ascending
  likeAsc,

  /// Sort by comments descending
  commentDesc,

  /// Sort by comments ascending
  commentAsc,
}
